package com.jrx.anytxn.accounting.job.subjectfile.config;

import com.jrx.anytxn.accounting.config.PathConfig;
import com.jrx.anytxn.accounting.entity.GaProductSummaryTransition;
import com.jrx.anytxn.accounting.entity.GaSubjectDetailTransition;
import com.jrx.anytxn.accounting.job.subjectfile.config.step.BuildFileListener;
import com.jrx.anytxn.accounting.mapper.ext.ExtGaProductSummaryTransitionMapper;
import com.jrx.anytxn.accounting.mapper.ext.ExtSubjectDetailTransitionMapper;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.JsonUtils;
import com.jrx.anytxn.param.entity.GaProductSummaryInfo;
import com.jrx.anytxn.param.entity.GaSubjectDetailInfo;
import com.jrx.anytxn.param.entity.GaSubjectSummaryInfo;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * 生成账务流水的·文件
 *
 * @author xqy
 * @version 1.0
 * @date 2019/11/28
 */
@Configuration
@EnableConfigurationProperties(PathConfig.class)
public class BuildFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(BuildFileConfiguration.class);

    @Autowired
    private PathConfig pathConfig;
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Resource
    private ExtSubjectDetailTransitionMapper extSubjectDetailTransitionMapper;
    @Resource
    private ExtGaProductSummaryTransitionMapper extGaProductSummaryTransitionMapper;
    @Autowired
    private BuildFileListener buildFileListener;

    @Bean
    public Job buildFileJob() throws Exception {
        return jobBuilderFactory.get("buildFileJob").incrementer(new RunIdIncrementer()).listener(buildFileListener)
                .start(buildDetailFileStep())
                .next(buildProductFileStep())
                .build();
    }

    @Bean
    public Step buildDetailFileStep() throws IOException {
        return stepBuilderFactory.get("buildDetailFileStep").tasklet(buildDetailFileTasklet()).build();
    }

    @Bean
    public Tasklet buildDetailFileTasklet() {
        return (stepContribution, chunkContext) -> {
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
            String today = DateUtils.format(org.getToday(),"yyyyMMdd");
            //创建科目明细表过渡表文件地址
            String subjectDetailPah = pathConfig.getBasePath() + "/subjectDetail/" + org.getTenantId();
            logger.info("科目明细表过渡表文件地址为:{}", subjectDetailPah);
            //创建科目总账过渡表文件地址
            String detailFileName = "detailBatch_" +pathConfig.getBatchTaskId() + "_" + today + ".txt";
            logger.info("科目明细表过渡表文件名为:{}", detailFileName);
            Path fpath = Paths.get(subjectDetailPah + "/" + detailFileName);
            Path pPath = Paths.get(subjectDetailPah);
            //判断文件是否存在
            if (!Files.exists(fpath)) {
                //判断文件夹是否存在
                if (!Files.isDirectory(pPath)) {
                    //创建文件夹
                    Files.createDirectories(pPath);
                }
                //创建文件
                Files.createFile(fpath);
            }
            List<GaSubjectDetailTransition> gaSubjectDetailTransitions = extSubjectDetailTransitionMapper.selectModalByDate(org.getToday());
            List<GaSubjectDetailInfo> gaSubjectDetailInfos = BeanMapping.copyList(gaSubjectDetailTransitions, GaSubjectDetailInfo.class);
            //创建FileWriter
            FileWriter bfw = new FileWriter(fpath.toFile());
            for (GaSubjectDetailInfo gaSubjectDetailInfo : gaSubjectDetailInfos) {
                bfw.write(JsonUtils.toJSon(gaSubjectDetailInfo));
                bfw.write("\n");
            }
            bfw.flush();
            bfw.close();
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public Step buildProductFileStep() {
        return stepBuilderFactory.get("buildProductFileStep").tasklet(buildProductFileTasklet()).build();
    }
    @Bean
    public Tasklet buildProductFileTasklet() {
        return (stepContribution, chunkContext) -> {
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
            String today = DateUtils.format(org.getToday(),"yyyyMMdd");
            //创建科目明细表过渡表文件地址
            String productSummaryPath =  pathConfig.getBasePath()  + "/productSummary/" + org.getTenantId();
            logger.info("产品余额汇总过渡表文件地址为:{}", productSummaryPath);
            //创建科目总账过渡表文件地址
            String summaryFileName = "productSummary_" + pathConfig.getBatchTaskId() + "_" + today + ".txt";
            logger.info("产品余额汇总过渡表文件名为:{}", summaryFileName);
            Path fpath = Paths.get(productSummaryPath + "/" + summaryFileName);
            Path pPath = Paths.get(productSummaryPath);
            //判断文件是否存在
            if (!Files.exists(fpath)) {
                //判断文件夹是否存在
                if (!Files.isDirectory(pPath)) {
                    //创建文件夹
                    Files.createDirectories(pPath);
                }
                //创建文件
                Files.createFile(fpath);
            }
            List<GaProductSummaryTransition> productSummaryTransitions = extGaProductSummaryTransitionMapper.selectByDate(org.getToday());
            if(CollectionUtils.isEmpty(productSummaryTransitions)){
                return RepeatStatus.FINISHED;
            }

            List<GaProductSummaryInfo> gaProductSummaryInfos = BeanMapping.copyList(productSummaryTransitions, GaProductSummaryInfo.class);
            //创建FileWriter
            FileWriter bfw = new FileWriter(fpath.toFile());
            for (GaProductSummaryInfo info : gaProductSummaryInfos) {
                bfw.write(JsonUtils.toJSon(info));
                bfw.write("\n");
            }
            bfw.flush();
            bfw.close();
            return RepeatStatus.FINISHED;
        };
    }

}